package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
* Created with IntelliJ IDEA.
* Description:
* User: nn
* Date: 2025-05-08
* Time: 下午2:27
*/public class UdpEchoClient {//客户端
    private DatagramSocket socket = null;
    private String serverip;
    private int serverport;//存储服务器的端口号

    public UdpEchoClient(String serveripip, int serverport) throws SocketException {
        socket = new DatagramSocket();
        this.serverip = serveripip;
        this.serverport = serverport;
    }

    public void start()throws IOException {
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入要发送的请求：");
            //1、从控制台读取用户输入
            String request = scanner.next();
            // 2. 构造请求并发送
            // 构造请求数据报的时候, 不光要有数据, 还要有 "目标"
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serverip),serverport);
            socket.send(requestPacket);
            //3.读取响应数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            //4.显示响应到控制台上
            String reponse = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(reponse);

        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9000);
        client.start();
    }

}
